<template>
  <div class="assignment-management">
    <a-card :bordered="false">
      <!-- 搜索表单 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="24" type="flex" align="middle">
            <a-col>
              <a-form-item label="作业标题">
                <a-input 
                  v-model:value="queryParams.title" 
                  placeholder="请输入作业标题" 
                  allowClear
                  @pressEnter="handleSearch"
                />
              </a-form-item>
            </a-col>
            <a-col>
              <a-form-item label="状态">
                <a-select 
                  v-model:value="queryParams.isPublished" 
                  placeholder="请选择状态" 
                  allowClear
                >
                  <a-select-option :value="1">已发布</a-select-option>
                  <a-select-option :value="0">未发布</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col flex="auto">
              <a-form-item>
                <a-space>
                  <a-button type="primary" @click="handleSearch">
                    <template #icon><search-outlined /></template>
                    查询
                  </a-button>
                  <a-button @click="handleReset">
                    <template #icon><reload-outlined /></template>
                    重置
                  </a-button>
                  <a-button type="primary" @click="handleAdd">
                    <template #icon><plus-outlined /></template>
                    新增作业
                  </a-button>
                </a-space>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <!-- 作业模板表格 -->
      <a-table
        :columns="columns"
        :data-source="assignmentList"
        :pagination="pagination"
        :loading="loading"
        rowKey="id"
        @change="handleTableChange"
      >
        <!-- 状态列自定义渲染 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'isPublished'">
            <a-tag :color="record.isPublished === 1 ? 'green' : 'orange'">
              {{ record.isPublished === 1 ? '已发布' : '未发布' }}
            </a-tag>
          </template>
          
          <!-- 操作列 -->
          <template v-if="column.dataIndex === 'action'">
            <span>
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除此作业模板吗?"
                ok-text="是"
                cancel-text="否"
                @confirm="handleDelete(record)"
              >
                <a>删除</a>
              </a-popconfirm>
              <a-divider type="vertical" />
              <a @click="handleToggleStatus(record)">
                {{ record.isPublished === 1 ? '撤回' : '发布' }}
              </a>
            </span>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { 
  getAssignmentTemplateList, 
  deleteAssignmentTemplate,
  updateAssignmentTemplate
} from '@/api/assignment'
import type { AssignmentTemplate, AssignmentTemplateListParams } from '@/api/assignment'
import { debounce } from 'lodash-es'
import { 
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined
} from '@ant-design/icons-vue'

const router = useRouter()

// 表格列定义
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: '5%',
  },
  {
    title: '作业标题',
    dataIndex: 'title',
    width: '20%',
  },
  {
    title: '描述',
    dataIndex: 'description',
    width: '30%',
    ellipsis: true,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: '15%',
    sorter: true,
  },
  {
    title: '状态',
    dataIndex: 'isPublished',
    width: '10%',
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '20%',
  }
]

// 查询参数
const queryParams = reactive<AssignmentTemplateListParams>({
  page: 1,
  pageSize: 10,
  title: '',
  isPublished: undefined,
  sortField: undefined,
  sortOrder: undefined
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: (total: number) => `共 ${total} 条记录`,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50', '100']
})

// 状态变量
const loading = ref<boolean>(false)
const assignmentList = ref<AssignmentTemplate[]>([])

// 获取作业模板列表数据
const fetchAssignmentList = async () => {
  try {
    loading.value = true
    const res = await getAssignmentTemplateList(queryParams)
    
    if (res.code === 200 && res.data) {
      assignmentList.value = res.data.result
      pagination.total = res.data.total
      pagination.current = queryParams.page
    } else {
      message.error(res.message || '获取作业模板列表失败')
    }
  } catch (error) {
    console.error('获取作业模板列表失败', error)
    message.error('获取作业模板列表失败')
  } finally {
    loading.value = false
  }
}

// 查询按钮点击事件
const handleSearch = debounce(() => {
  queryParams.page = 1
  fetchAssignmentList()
}, 500)

// 重置按钮点击事件
const handleReset = () => {
  queryParams.title = ''
  queryParams.isPublished = undefined
  queryParams.sortField = undefined
  queryParams.sortOrder = undefined
  queryParams.page = 1
  fetchAssignmentList()
}

// 表格变化事件
const handleTableChange = (pag: any, _filters: any, sorter: any) => {
  // 同步更新分页参数
  queryParams.page = pag.current
  queryParams.pageSize = pag.pageSize
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  
  // 处理排序
  if (sorter && sorter.field && sorter.order) {
    queryParams.sortField = sorter.field
    queryParams.sortOrder = sorter.order === 'ascend' ? 'asc' : 'desc'
  } else {
    queryParams.sortField = undefined
    queryParams.sortOrder = undefined
  }
  
  fetchAssignmentList()
}

// 新增按钮点击事件
const handleAdd = () => {
  router.push('/assignment/edit')
}

// 编辑按钮点击事件
const handleEdit = (record: AssignmentTemplate) => {
  if (record.id) {
    router.push(`/assignment/edit/${record.id}`)
  } else {
    message.error('记录ID不存在')
  }
}

// 删除按钮点击事件
const handleDelete = async (record: AssignmentTemplate) => {
  if (!record.id) {
    message.error('记录ID不存在')
    return
  }
  
  try {
    const res = await deleteAssignmentTemplate(record.id)
    if (res.code === 200) {
      message.success('删除作业模板成功')
      fetchAssignmentList()
    } else {
      message.error(res.message || '删除作业模板失败')
    }
  } catch (error) {
    console.error('删除作业模板失败', error)
    message.error('删除作业模板失败')
  }
}

// 切换状态按钮点击事件
const handleToggleStatus = async (record: AssignmentTemplate) => {
  if (!record.id) {
    message.error('记录ID不存在')
    return
  }
  
  const newStatus = record.isPublished === 1 ? 0 : 1
  const statusText = newStatus === 1 ? '发布' : '撤回'
  
  try {
    const res = await updateAssignmentTemplate({
      id: record.id,
      title: record.title,
      isPublished: newStatus
    } as AssignmentTemplate)
    
    if (res.code === 200) {
      message.success(`${statusText}作业模板成功`)
      // 更新本地数据
      record.isPublished = newStatus
    } else {
      message.error(res.message || `${statusText}作业模板失败`)
    }
  } catch (error) {
    console.error(`${statusText}作业模板失败`, error)
    message.error(`${statusText}作业模板失败`)
  }
}

// 页面加载时获取作业模板列表
onMounted(() => {
  fetchAssignmentList()
})
</script>

<style lang="less" scoped>
.assignment-management {
  .table-page-search-wrapper {
    margin-bottom: 24px;
    padding: 24px;
    background-color: #fafafa;
    border-radius: 4px;
    
    .ant-form-item {
      margin-bottom: 0;
    }
  }
  
  // 移动端适配
  @media (max-width: 768px) {
    .ant-form-inline .ant-form-item {
      margin-bottom: 16px;
    }
    
    .ant-form-item-control-wrapper {
      display: block;
    }
  }
}
</style> 